package server.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 服务器
 * @author skywalker
 *
 */
public class Server {
	
	private static final int port = 8080;
	private ServerSocket serverSocket;
	private volatile boolean started = true;
	//线程池
	private final ExecutorService service = Executors.newFixedThreadPool(10);
	private final Logger logger = LogManager.getLogger("server.server.Server");
	
	/**
	 * 启动服务器
	 */
	public void start() {
		try {
			serverSocket = new ServerSocket(port);
			logger.info("服务器启动成功");
			while (started) {
				final Socket socket = serverSocket.accept();
				logger.info(socket.getInetAddress().toString() + "连接到服务器");
				service.execute(new Worker(socket));
			}
		} catch (IOException e) {
			logger.fatal("服务器发生异常，正在停止");
			logger.fatal(e.getMessage());
		}
	}
	
	/**
	 * 关闭服务器
	 */
	public void stop() {
		started = false;
		logger.info("服务器已停止");
		service.shutdown();
	}

}
